package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单明细
 */
@Slf4j
@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 后台分页查询订单信息 。
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String number,String beginTime,String endTime){ // page?page=1&pageSize=10&number=15391414&beginTime=2022-06-21%2000%3A00%3A00&endTime=2022-06-22%2023%3A59%3A59
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Orders::getOrderTime);
        queryWrapper.like(number!=null,Orders::getId,number); // getNumber也可以
        queryWrapper.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.
                isNotEmpty(endTime),Orders::getOrderTime,beginTime,endTime);
        ordersService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);

    }


    /**
     * 提交订单。
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);

        return R.success("订单提交成功！");
    }

    /**
     * 用户查看的 历史订单。
     * 需要显示 订单明细，什么菜品等等
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page,Integer pageSize){ // ?page=1&pageSize=5
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> dtoPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Orders::getOrderTime);
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        ordersService.page(pageInfo,queryWrapper);


        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Orders> ordersList = pageInfo.getRecords();

        List<OrdersDto> list =
                ordersList.stream().map((item)->{
                    OrdersDto ordersDto = new OrdersDto();

                    // 寻找 List<OrderDetail>
                    LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(OrderDetail::getOrderId,item.getId());
                    List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper1);

                    // 设置并且拷贝。
                    BeanUtils.copyProperties(item,ordersDto);
                    ordersDto.setOrderDetails(orderDetails);
                    return  ordersDto;
                }).collect(Collectors.toList());


        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }

    /**
     * 后台 根据id 修改订单状态值，也就是派送..
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> status(@RequestBody Orders orders){ //{status: 3, id: "1538937603523424258"}
        ordersService.updateById(orders);

        return R.success("订单派送成功!");
    }
    /**
     * 订单 再来一单
     * 要将该订单的商品 加入到购物车上。
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Map<String,String> map) { //id: 1539141431229243394"  订单的id 订单号。
        String ids = map.get("id");
        Long id = Long.parseLong(ids);
        // 分析：需要跳到订单页面 购物车存在该数据。-->清空之前存在购物车的数据。
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);

        // 处理shopping_cart 表，删除所有关于本id的 购物车信息
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ShoppingCart::getUserId,currentId);
        shoppingCartService.remove(queryWrapper1);  // 这里可以进行复用clean

        // 添加购物车信息
        List<ShoppingCart> shoppingCartList =
        orderDetails.stream().map((item)->{
            ShoppingCart shoppingCart = new ShoppingCart();

            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(currentId);
            // 看着里面是 菜品 还是 套餐。
            Long setmealId = item.getSetmealId();
            Long dishId = item.getDishId();
            if(setmealId != null){
                shoppingCart.setSetmealId(setmealId);
            }else{
                shoppingCart.setDishId(dishId);
            }
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功！");

    }

}
